package cn.zyx.config.shiro;

import cn.zyx.common.GlobalErrorController;
import cn.zyx.common.utils.CookieUtils;
import cn.zyx.common.utils.sys.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义shiro过滤器
 * BasicHttpAuthenticationFilter : 用户身份认证
 * Shiro框架所有的请求经过过滤器
 * isAccessAllowed：判断是否登录
 * 在登录的情况下会走此方法，此方法返回true直接访问控制器
 * onAccessDenied：是否是拒绝登录
 * 没有登录的情况下会走此方法
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //@Autowired
    //private GlobalProperties properties;

    /**
     * 对跨域提供支持  协议 域名 端口 不同都会造成跨域
     * 拦截器的前置  最先执行的 这里只做了一个跨域设置
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        logger.debug("preHandle 跨域处理");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACES");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept,Origin,X-Requested-With,Content-Type,X-Auth-Token");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }

    /**
     * 判断用户是否要执行登录
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        logger.debug("isAccessAllowed JWTFilter 用户执行登录逻辑");
        if (isLoginAttempt(request, response)) {
            try {
                return executeLogin(request, response);
            } catch (AuthenticationException e) {
                // 登录超时，需要刷新token
                GlobalErrorController.response401(request, response);
                logger.debug("登录超时，需要刷新token");
            } catch (Exception e) {
                // 没有登录，需要登录
                GlobalErrorController.response4021(request, response);
                logger.debug("没有登录，需要登录");
            }
        } else {
            // 没有登录，需要登录
            GlobalErrorController.response4021(request, response);
            logger.debug("没有登录，需要登录");
        }
        return false;

    }


    /*
     * 判断用户是否想要登入。
     * 检测header里面是否包含Token字段即可
    */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        logger.debug("isLoginAttempt 用户是否想要登入");
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = getToken(req);
        return authorization != null && !"null".equals(authorization) && !authorization.isEmpty();
    }

    /**
     * 执行登陆
     * 因为已经判断token不为空了,所以直接执行登陆逻辑
     * 将token放入JwtToken类中去
     * 然后getSubject方法是调用到了MyRealm的 执行方法  因为上面我是抛错的所有最后做个异常捕获就好了
     * */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        logger.debug("executeLogin 执行登陆");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String authorization = getToken(httpServletRequest);

        JWTToken token = new JWTToken(authorization);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(token);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /*
     * 获取token，支持三种方式, 请求参数、header、cookie， 优先级依次降低，以请求参数中的优先级最高。
     *
     * @param httpServletRequest
     * @return
     * */
    private String getToken(HttpServletRequest httpServletRequest) {
        String token0 = httpServletRequest.getParameter(JWTUtils.TOKEN);
        String token1 = httpServletRequest.getHeader(JWTUtils.TOKEN);
        String token2 = CookieUtils.getCookie(httpServletRequest, JWTUtils.TOKEN);
        if (StringUtils.isNotBlank(token0)) {
            return token0;
        }
        if (StringUtils.isNotBlank(token1)) {
            return token1;
        }
        if (StringUtils.isNotBlank(token2)) {
            return token2;
        }
        return null;
    }
}
